<template>
  <div>
    <div class="form-item">
      <div class="label"><span class="require">*</span> 选取字段</div>
      <div class="field-list">
        <div v-for="(item, index) in dataForm.selectField" :key="index" class="field-item">
          <template v-if="!item.fieldType">
            <el-input v-model="item.columnName" :maxlength="20" class="width120 mr12" placeholder="请输入列名称" size="small" type="text" />
            <selectWithoutHttp
              v-model="item.sourceId"
              :list-data="systemConditionOptions"
              class="width120 mr12"
              placeholder="选择数据表"
              key-name="id"
              label-name="name"
              filterable
              clearable
              @change="fieldCategorysChange($event, item)"
            />
            <selectWithoutHttp
              v-model="item.fieldName"
              :list-data="item.fieldChidrenList"
              :class="{'mr12': index === 0}"
              class="width120"
              placeholder="选择字段"
              key-name="name"
              label-name="name"
              filterable
              clearable
              @change="fieldNameChange($event, item)"
            />
            <template v-if="index !== 0">
              <span class="tip-word">的</span>
              <el-select v-model="item.formula" clearable size="small" popper-class="global-select-down" class="width120 mr12" name="field">
                <el-option
                  v-for="item in filedFormulaOpt"
                  :key="item"
                  :label="item"
                  :value="item" />
              </el-select>
            </template>
          </template>
          <div v-else>
            <!-- 公式字段 -->
            <div style="margin-bottom:10px;">
              <el-input v-model="item.columnName" class="width120 mr12" maxlength="20" placeholder="请输入列名称" size="small" type="text" />
            </div>
            <div class="formula-container">
              <!-- <OverviewFormula v-if="Array.isArray(item.formulaOrigin)" v-model="item.formulaOrigin" :tags-options="handelData(dataForm.selectField)" quote-label-placeholder="请选择引用的列" value-key="columnName" quote-label-name="引用列" />
              <div style="display:flex;align-items:center;">
                <div style="color:#606266;width:80px;text-align:right;padding-right:10px;font-size:14px;">单位</div>
                <el-input v-model="item.unit" size="small" class="width240" placeholder="不超过10个字符" maxlength="10" />
              </div> -->
              <div v-if="item.showEditTagFormula">
                <OverviewFormula v-if="Array.isArray(item.formulaOrigin)" v-model="item.formulaOrigin" :tags-options="handelData(dataForm.selectField)" quote-label-placeholder="请选择引用的列" value-key="columnName" quote-label-name="引用列" />
                <div style="display:flex;align-items:center;">
                  <div style="color:#606266;width:80px;text-align:right;padding-right:10px;font-size:14px;">单位</div>
                  <el-input v-model="item.unit" size="small" class="width240" placeholder="不超过10个字符" maxlength="10" />
                </div>
                <div class="center btns">
                  <el-button class="ok submit-btn" type="primary" size="small" @click="handleConfirm(item, 1)">确定</el-button>
                  <el-button class="back-btn cancel-btn-style" size="small" @click="handleConfirm(item, 0)">取消</el-button>
                </div>
              </div>
              <el-form v-else>
                <el-form-item label="配置公式" label-width="80px">
                  <span class="light-word" @click="handleEditTagFormula(item)">{{ showFormula(item) }}</span>
                </el-form-item>
                <el-form-item label="单位" label-width="80px">
                  <span class="light-word" @click="handleEditTagFormula(item)">{{ item.unit || '请输入单位' }}</span>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div :class="{'float': item.fieldType}" class="tool-bar">
            <template v-if="index !== 0">
              <div class="delete-btn" @click="deleteItem(index)">
                <i class="delete-icon el-icon-delete" />
              </div>
              <!-- 向上 -->
              <el-tooltip content="往前移" placement="top">
                <i v-if="index > 1" class="index-icon el-icon-top" @click="changeIndex('top',index)"/>
                <i v-else class="index-icon el-icon-top" style="color:#999;cursor:not-allowed;" />
              </el-tooltip>
              <!-- 向下 -->
              <el-tooltip content="往后移" placement="top">
                <i v-if="index !== dataForm.selectField.length-1" class="index-icon el-icon-bottom" @click="changeIndex('bottom',index)"/>
                <i v-else class="index-icon el-icon-bottom" style="color:#999;cursor:not-allowed;" />
              </el-tooltip>
              <!-- 复制 -->
              <el-tooltip content="复制" placement="top">
                <i class="index-icon el-icon-copy-document" @click="copyTag(item)" />
              </el-tooltip>
            </template>
            <el-tooltip :content="`隐藏标签:${item.hideTag === 1?'隐藏':'显示'}`" placement="top">
              <i :style="item.hideTag === 1?{color: '#999'}:{color: '#406eff'}" class="eye-icon el-icon-view" @click="changeTag(item)"/>
            </el-tooltip>
            <el-tooltip :content="`设为唯一值${index === 0?'：不可取消':''}`" placement="top">
              <i :style="item.uniqueFlag === 1 || index === 0?{color: '#406eff'}:{color: '#999'}" class="eye-icon el-icon-key" @click="changeUniqueFlag(item, index)"/>
            </el-tooltip>
          </div>
        </div>
        <div>
          <PlainCreateBtn size="small" @click="addItem(0)">添加列</PlainCreateBtn>
          <PlainCreateBtn size="small" @click="addItem(1)">添加公式列</PlainCreateBtn>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import ElMessage from '@/utils/message';
import OverviewFormula from '@/components/ReportManage/chartCreate/module/overviewFormula';

export default {
  components: { selectWithoutHttp, OverviewFormula },
  model: {
    prop: 'dataForm',
    event: 'changeData'
  },
  props: {
    dataForm: {
      type: Object,
      default: () => ({})
    },
    systemConditionOptions: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      filedFormulaOpt: ['求和', '平均数', '计数', '计数(去重)', '求和-同比', '求和-环比', '计数-同比', '计数(去重)-同比', '计数-环比', '计数(去重)-环比']
    };
  },
  methods: {
    showFormula(item) {
      let res = '';
      if (Array.isArray(item.formulaOrigin) && item.formulaOrigin.length) {
        res = item.formulaOrigin.reduce((res, cur) => {
          if (cur.type === 'var') {
            return res + '' + (cur.columnName || cur.fieldName);
          } else {
            return res + '' + cur.tagName;
          }
        }, '');
      } else {
        res = '请输入公式';
      }
      return res;
    },
    /**
     * change 事件
     */
    fieldCategorysChange(id, item) {
      item.fieldName = '';
      item.optionsType = '';
      item.formula = '';
      const dataSheetItem = this.systemConditionOptions.find(i => i.id === id);
      if (dataSheetItem) {
        item.sourceName = dataSheetItem.name;
        dataSheetItem.field.forEach(i => {
          i.sourceId = id;
          i.sourceName = dataSheetItem.name;
        });
        item.fieldChidrenList = dataSheetItem.field;
      } else {
        item.fieldChidrenList = [];
      }
      this.changeData();
    },
    fieldNameChange(data, item) {
      const fieldItem = item.fieldChidrenList.find(i => i.name === data);
      item.optionsType = fieldItem.optionsType;
      item.columnName = data;
      item.fieldKey = fieldItem.fieldKey;
      item.uniqueId = fieldItem.uniqueId;
      this.changeData();
    },
    /**
     * 操作
     */
    addItem(type) {
      const item = {
        fieldType: type,
        columnName: '',
        fieldId: '',
        formula: '',
        fieldName: '',
        reportId: '',
        hideTag: 0,
        uniqueFlag: 0,
        uniqueId: ''
      };
      if (type === 1) { // 公式字段
        item.tagFormula = '';
        item.formulaVariable = [];
        item.formulaOrigin = []; // 原数据
        item.unit = '';
        item.showEditTagFormula = false;
        // item.tagFormulaText = '';
      }
      this.dataForm.selectField.push(item);
      this.changeData();
    },
    changeTag(item) {
      item.hideTag = item.hideTag === 1 ? 0 : 1;
    },
    changeUniqueFlag(item, index) {
      if (index === 0) return;
      item.uniqueFlag = item.uniqueFlag === 1 ? 0 : 1;
    },
    deleteItem(index) {
      this.dataForm.selectField.splice(index, 1);
      this.changeData();
    },
    // 上移下移
    changeIndex(type, index) {
      const arr = this.dataForm.selectField.splice(index, 1);
      if (type === 'bottom') {
        this.dataForm.selectField.splice(index + 1, 0, arr[0]);
      } else if (type === 'top') {
        this.dataForm.selectField.splice(index - 1, 0, arr[0]);
      }
      this.changeData();
    },
    copyTag(item) {
      let formulaOrigin = [];
      if (item.formulaOrigin && item.formulaOrigin.length) {
        formulaOrigin = [...item.formulaOrigin];
      }
      const tagItem = _.cloneDeep(item);
      tagItem.formulaOrigin = formulaOrigin;

      let index = 0;
      const tagName = `${tagItem.columnName}-副本`;
      this.dataForm.selectField.forEach(i => {
        if (i.columnName.indexOf(tagName) >= 0) {
          index++;
        }
      });
      if (index > 0) {
        tagItem.columnName = tagName + index;
      } else {
        tagItem.columnName = tagName;
      }
      this.dataForm.selectField.push(tagItem);
      ElMessage.success('复制成功');
      this.changeData();
    },
    handelData(fields) {
      const res = fields.filter(i => {
        return !i.fieldType && i.columnName;
      });
      return res;
    },
    changeData() {
      this.$emit('changeData', this.dataForm);
    },
    handleConfirm(item, flag) {
      item.showEditTagFormula = false;
      if (!flag) {
        item.formulaOrigin = item.oldFormulaOrigin;
      }
      /* if (flag) {
        item.tagFormulaText = item.formulaOrigin.reduce((res, cur) => {
          if (cur.type === 'var') {
            return res + '' + (cur.columnName || cur.fieldName);
          } else {
            return res + '' + cur.tagName;
          }
        }, '');
      } else {
        item.formulaOrigin = item.oldFormulaOrigin;
      } */
    },
    handleEditTagFormula(item) {
      item.showEditTagFormula = true;
      item.oldFormulaOrigin = JSON.parse(JSON.stringify(item.formulaOrigin));
    }
  }
};
</script>

<style lang="scss" scoped>
.form-item {
  display: flex;
  margin-bottom: 24px;
  .label {
    text-align: right;
    font-size: 14px;
    color: #666;
    margin-right: 10px;
    width: 100px;
    line-height: 32px;
    display: flex;
    justify-content: flex-end;
    .require {
      color: #F56C6C;
      margin-right: 4px;
    }
  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.width120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
.mr12 {
  margin-right: 12px;
}
.field-item {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  position: relative;
  &:last-child {
    margin-bottom: 0;
  }
}
.flex-center {
  display:flex;align-items:center;
}
.tool-bar {
  display: flex;
  align-items:center;
  &.float {
    position: absolute;
    top: 0;
    left: 130px;
  }
  img {
    cursor: pointer;
    width: 16px;
  }
}
.eye-icon {
  font-size: 16px;
  cursor: pointer;
  color: #406eff;
  margin-right: 10px;
}
.index-icon {
  font-size: 16px;
  cursor: pointer;
  color: #406eff;
  margin-right: 10px;
}
.delete-btn {
  margin-left: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  cursor: pointer;
  .delete-icon {
    font-size: 16px;
    color: #6C6C6C;
  }
}
.formula-container {
  min-width:616px;
  display: inline-block;
  border-radius:4px;
  border:1px solid #DCDFE6;
  padding: 20px 20px 20px 28px;
  .center {
    display: flex;
    justify-content: center;
    margin-top: 15px;
  }
  .el-form{
    &::v-deep{
      .el-form-item{
        margin: 0;
        .light-word{
          color: #406eff;
          cursor: pointer;
        }
      }
    }
  }
}
.tip-word {
  font-size:14px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(153,153,153,1);
  line-height:14px;
  margin: 0 7px;
}
</style>
